﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace QW.Core.Encrypt
{
    /// <summary>
    /// Base64工具
    /// </summary>
    public sealed class Base64Helper
    {
        /// <summary>
        /// 编码
        /// <para>默认UTF8</para>
        /// </summary>
        /// <param name="encode"></param>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Encode(string str,Encoding encode=null)
        {
            if (encode == null)
            {
                encode = Encoding.UTF8;
            }
            byte[] bytes = encode.GetBytes(str);
            string rstr = "";
            try
            {
                rstr = Convert.ToBase64String(bytes);
            }
            catch
            {
                rstr = str;
            }
            return rstr;
        }
        /// <summary>
        /// 还原
        /// <para>默认UTF8</para>
        /// </summary>
        /// <param name="str"></param>
        /// <param name="encode"></param>
        /// <returns></returns>
        public static string Decode(string str, Encoding encode = null)
        {
            if (encode == null)
            {
                encode = Encoding.UTF8;
            }
            string decode = "";
            byte[] bytes = Convert.FromBase64String(str);
            try
            {
                decode = encode.GetString(bytes);
            }
            catch
            {
                decode = str;
            }
            return decode;
        }
    }
}
